﻿using System.Collections.Generic;

namespace Behaviours.Entities
{
    /// <summary>
    /// 通过类订阅
    /// </summary>
    public interface IObserver
    {
        void Update(Observable observable);
    }
    public abstract class Observable
    {
        List<IObserver> _observers = new List<IObserver>();

        public void Subscribe(IObserver subscribe)
        {
            this._observers.Add(subscribe);
        }
        
        public void UnSubscribe(IObserver subscribe)
        {
            this._observers.Remove(subscribe);
        }
        public void Update()
        {
            foreach(var x in _observers)
            {
                x.Update(this);
            }
        }
    }

    /// <summary>
    /// 通过事件订阅
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Observable<T>
    {
        public delegate void ObserverSubscribe(T t);
        private ObserverSubscribe _subscribe;
        private T _pram;
        
        public Observable(T val)
        {
            _pram = val;
        }
        
        public void Update()
        {
            if(_subscribe != null)
                _subscribe.Invoke(_pram);
        }
        
        public Observable<T> Subscribe(ObserverSubscribe subscribe)
        {
            this._subscribe += subscribe;
            return this;
        }
        
        public Observable<T> UnSubscribe(ObserverSubscribe subscribe)
        {
            this._subscribe -= subscribe;
            return this;
        }
    }
}